<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2021-08-03
 * Time: 9:37
 */

namespace app\common\service;


use app\common\exception\ServiceException;
use app\common\item\UploadLoader;
use app\common\model\UploadModel;
use app\common\pipeline\BaseItemAdapter;
use app\common\util\FFMpegUtil;
use app\common\util\TencentUploadUtil;
use Qcloud\Cos\Client;
use think\facade\Env;
use think\facade\Hook;


class UploadService
{


    /**
     * 添加到临时文件夹先 并返回信息
     */
    protected static function getTmpPath()
    {
        $tmp_path = Env::get("app_path") . "/../public/tmp";
        if (!is_dir($tmp_path)) {
            if (!mkdir($tmp_path, 0777, true) && !is_dir($tmp_path)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $tmp_path));
            }
        }
        return $tmp_path;
    }

    protected static function getFilename($path)
    {
        $filename = explode("/", $path);
        return end($filename);
    }

    protected static function formal($platform, $path)
    {
        $path = str_replace('\\', '/', $path);
        $filename = self::getFilename($path);
        $url = "";
        $upload_dir = '/' . date("Ymd") . '/' . date("H");
        $upload_path = $upload_dir . "/" . $filename;
        if ($platform == UploadLoader::PLATFORM_LOCAL) {//存储到本地
            $local_path = Env::get("app_path") . "/../public/user" . $upload_dir;
            if (!is_dir($local_path)) {
                if (!mkdir($local_path, 0777, true) && !is_dir($local_path)) {
                    throw new \RuntimeException(sprintf('Directory "%s" was not created', $local_path));
                }
            }
            $local_path = realpath($local_path);
            $save_path = $local_path . "/" . $filename;
            copy($path, $save_path);
            $url = str_replace(["\\", "//"], "/", $save_path);
            $url = substr($url, strpos($url, "/public/") + (strlen("/public/") - 1));
        } elseif ($platform == UploadLoader::PLATFORM_COS) { //腾讯云上传
            $url = TencentUploadUtil::upload($path, $upload_path);
        }
        return $url;
    }

    public static function uploadVideoCover($file_path, $platform)
    {
        $url = '';
        try {
            $ffmpeg_util = FFMpegUtil::Instance();
            $move_path = self::getTmpPath();
            $cover_tmp_img_path = $move_path . "/" . uniqid('', true) . ".jpg";
            $ffmpeg_util->getScreenshot($file_path, $cover_tmp_img_path);
            if (is_file($cover_tmp_img_path)) {
                $url = self::formal($platform, $cover_tmp_img_path);
                @unlink($cover_tmp_img_path); //删除临时文件
            }
        } catch (\Exception $exception) {
        }
        return $url;
    }

    public static function upload($form_name = "file", $params = [])
    {
        $platform = isset($params['platform']) ? $params['platform'] : get_sysconfig("upload_platform");
        $move_path = self::getTmpPath();
        $loader = new UploadLoader();
        $data = $loader->getFieldInfo($form_name, $move_path, $params);
        $path = $data['path']; //文件所在路径
        unset($data['path']);
        $formal_url = self::formal($platform, $path); //正式的url链接
        $data['platform'] = $platform;
        $data['url'] = $formal_url;
        if ($data['type'] == UploadLoader::UPLOAD_VIDEO) { //处理方面图
            //生成一个封面图片
            $data['cover_images'] = self::uploadVideoCover($path, $platform);
        } else {
            $data['cover_images'] = "";
        }
        $adapter = new BaseItemAdapter(UploadModel::class);
        $adapter->save($data);
        @unlink($path);
        return ["upload_id" => $adapter->getId(), "title" => $data['title'], "src" => $data['url'], "cover_images" => $data['cover_images']];
    }
}